package com.vikutorika.service;

import cn.hutool.crypto.digest.BCrypt;
import com.vikutorika.dao.imp.SuspensionInfoDAOImp;
import com.vikutorika.dao.imp.UserInfoDAOImp;
import com.vikutorika.entity.SuspensionInfo;
import com.vikutorika.vo.ResultVo;
import com.vikutorika.dao.UserInfoDAO;
import com.vikutorika.entity.UserInfo;

import java.sql.Date;
import java.sql.Timestamp;

public class UserService {
    public ResultVo login(UserInfo userInfo) {
        UserInfoDAO dao = new UserInfoDAOImp();
        SuspensionInfoDAOImp suspensionInfoDAOImp = new SuspensionInfoDAOImp();
        UserInfo info = dao.getByPhoneNumber(userInfo.getPhone());
        if (info != null) {
            if (BCrypt.checkpw(userInfo.getPassword_hash(), info.getPassword_hash())) {
                info.setPassword_hash("******");
                SuspensionInfo suspensionInfo = suspensionInfoDAOImp.getByUID(info.getUid());
                if (suspensionInfo != null) {
                    Timestamp endTime = suspensionInfo.getEnd_time();
                    Timestamp now = new Timestamp(new java.util.Date().getTime());
                    if (endTime.after(now))
                        return ResultVo.error("账号封禁中");
                }
                return ResultVo.success("登录成功", info);
            }
        }
        return ResultVo.error("账号密码错误");
    }

    public ResultVo enroll(UserInfo userInfo) {
        UserInfoDAO dao = new UserInfoDAOImp();
        String password = BCrypt.hashpw(userInfo.getPassword_hash());
        userInfo.setPassword_hash(password);
        userInfo.setNickname(userInfo.getNickname());
        boolean b = dao.insert(userInfo);
        if (!b)
            return ResultVo.error("注册失败");
        return ResultVo.success("注册成功");
    }
}
